
#include "ShaderBuffer.h"

ShaderBuffer::ShaderBuffer(ShaderVertexDataPtr pVertexData)
	: m_pVertexData(pVertexData)
	, m_vbo(0)
{

}

void ShaderBuffer::initBinding()
{
	ShaderVertex::initBinding();
	if (!m_pVertexData)	return;

	glGenBuffers(1, &m_vbo);
	glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
	glBufferData(GL_ARRAY_BUFFER, m_pVertexData->getDataSize(), m_pVertexData->getData(), GL_STATIC_DRAW);

	int idx = 0;
	for (auto it = m_pVertexData->getVertexAttrib().begin(); it != m_pVertexData->getVertexAttrib().end(); it++)
	{
		glVertexAttribPointer(idx, (*it)->getVertexSize(), GL_FLOAT, GL_FALSE, m_pVertexData->getVertexSize() * sizeof(GLfloat), (GLvoid*)((*it)->getVertexIndex() * sizeof(GLfloat)));
		glEnableVertexAttribArray(idx++);
	}
}

void ShaderBuffer::cleanBinding()
{
	ShaderVertex::cleanBinding();
	if (m_vbo > 0)
	{
		glBindBuffer(GL_ARRAY_BUFFER, 0);
		glDeleteBuffers(1, &m_vbo);
		m_vbo = 0;
	}
	m_pVertexData = nullptr;
}

void ShaderBuffer::draw(GLuint vertexSize, GLuint vertexIndex)
{
	glDrawArrays(GL_TRIANGLES, vertexIndex, vertexSize);
}
